package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import cn.com.dstz.agent.config.NoticeConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.data.post.IP_PropertiesLoad;
import cn.com.dstz.data.post.NoticeKeyVal;
import cn.com.dstz.data.post.Post;
import cn.com.dstz.data.post.PostTask;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 公告管理
 * @author 叶装装
 * 2013-5-22 22:00 修复完成
 * 2013 -06-04 20:32 二次修复
 * 2013-06-07 :18:38 三次修复   经测试，完全可以满足要求
 * @since 1.6
 * 
 */
public class NoticeAct extends BaseAction{
	
	@SuppressWarnings( "unchecked" )
	public void list( ){
		
		String sql = "select g.*, a.username, n.name,n.level from dstzgg g, dstzadmin a, dstz_noticetype n where g.adminid = a.id and g.ggtype = n.id ";
		//String sql = "select g.*, a.username, n.name,n.level from dstzgg g, dstzadmin a, dstz_noticetype n where g.adminid = a.id ";
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );// 查看等级
		
		Map< String, Object > valueMap = null;
		
		if( level > 0 ){
			NoticeConfig config = new NoticeConfig( admin, this.countManagerGroup( ));
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
		}
		
		Map< String, Object > resultMap = this.paginationBySQL( sql, null, valueMap, "g.sendtime" );
		
		List< Map< String, Object >> resultList = ( List< Map< String, Object >>) resultMap.get( "rows" );
		
		// 放入简介信息
		for( Map< String, Object > result : resultList ){
			String content = ( String ) result.get( "content" );
			content = Jsoup.clean( content, Whitelist.none( ) );
			int len = content.length( );
			
			if( len > 30 ){
				content = content.substring( 0, 30 ) + "...";
			}
			result.put( "content", content );
		}
		
		this.responseToJsonObject( resultMap  );
		
		return;
		
	}
	
	public String toadd( ){
		return "add";
	}
	
	public void add( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin ); // 查看等级
		
		int getNoticeTypeId = getNoticeTypeId( level );
		
		if( getNoticeTypeId == 0 ){
			this.ajaxResponse( 2 );
			return;
		}
		
		int validSaveOrUpdate = validSaveOrUpdate(  0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		int save = baseService.save( "dstzgg", DataBaseUtils.getData( new String[]{
				"aid", "adminid", "ggtype", "content", "sendtime"
		}, new Object[]{
				admin.get( "topaid" ), admin.get( "id" ), getNoticeTypeId, content, DateUtils.getCurrentTime( )
		} ) );
		
		// post 数据
		if( level > 0 && save > 0 ){
			Post post = new Post( IP_PropertiesLoad.getInstance( ).getIps( ), new NoticeKeyVal( admin.get( "topaid" ), content ) );
			postTask.addTask( post );
		}
		
		this.addLog( save, "notice", 0,  "" );
		
		this.ajaxResponse( save > 0 ? 0 : -1 );
		return;
	}
	
	public String toedit( ){
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.alertMsg( null );
			return "edit";
		}
		
		String sql = "select g.*, a.username, n.name,n.level from dstzgg g, dstzadmin a, dstz_noticetype n where g.adminid = a.id and g.ggtype = n.id and g.id=:id";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "id", id );
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		getRequest( ).setAttribute( "data", data );
		
		return "edit";
	}
	
	public void edit( ){
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin ); // 查看等级
		
		Map< String, Object > whereData = new HashMap< String, Object >( );
		
		whereData.put( "id", id );
		
		if( level > 0 ){
			whereData.put( "adminid", admin.get( "id" ) );
		}
		
		int update = baseService.update( "dstzgg", DataBaseUtils.getData( new String[]{
				"content"
		}, new Object[]{
				content
		} ), whereData );
		
		this.addLog( update, "notice", 1, "ID：" + id );
		
		int response =  update > 0 ? 0 : -1;
		
		if( level > 0 && response == -1 ){
			response = -99;
		}
		
		this.ajaxResponse( response );
		
		return;
	}
	
	public void delete( ){
		String ids = getParameter( "ids" );
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin ); // 查看等级
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						String delSql = "delete from dstzgg where id=" + id;
						if( level > 0 ){
							delSql += " and adminid=" + admin.get( "id" );
						}
						
						updateSqlList.add(  delSql );
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "notice", 2, ids );
			}
		}
	}
	
	/**
	 * 根据分组的等级获取公告类型
	 * @param adminLevel
	 * @return
	 */
	private int getNoticeTypeId( int adminLevel ){
		
		String sql = "select id from dstz_noticetype where 1=1";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		
		if( adminLevel == 0 ){
			sql += " and level=:level";
		}else{
			sql += " and level !=:level";
			adminLevel = 0;
		}
		
		valueMap.put( "level", adminLevel );
		
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		
		if( data == null || data.isEmpty( ) ){
			return 0;
		}
		
		return ( Integer ) data.get( "id" );
		
		
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		if( saveOrUpdate == 2 || saveOrUpdate == 1){
			if( id == null || id == 0 ){
				return 2;
			}
			if( saveOrUpdate == 2 ){
				return 0;
			}
		}
		
		if( ValidUtils.validLength( content, 5, 2000 )){
			return 1;
		}
		
		return 0;
	}
	
	private String content;
	private Integer id;
	
	public String getContent( ) {
		return content;
	}
	

	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	public void setContent( String content ) {
		if( StringUtils.isNotBlank( content )){
			content = decode( content );
		}
		this.content = content;
	}

	private static final long serialVersionUID = 1L;
	
	private PostTask postTask;

	public PostTask getPostTask( ) {
		return postTask;
	}

	public void setPostTask( PostTask postTask ) {
		this.postTask = postTask;
	}
	
}
